﻿namespace PhoneSuiteReader
{
    using Microsoft.Win32;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;

    internal class MainClass
    {


        public static void DoEvent(string fileName, string saveFileName)
        {
            string str = ReadFile(fileName);
            byte[] buffer = null;
            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                buffer = new byte[stream.Length];
                stream.Read(buffer, 0, (int) stream.Length);
            }
            List<Model> list = DoListItem(buffer);
            StreamWriter writer = new StreamWriter(saveFileName);

            foreach (Model model in list)
            {
                writer.Write("{0} \t; {1} \t; {2} \t; {3} \t; {4} \t; {5} \t; \r\n"
            	             , model.Date, model.Number, model.Position
            	            , model.Date2, model.ISPNumber, model.Msg
            	           );
            }
            writer.Flush();
            writer.Close();
            writer = null;
        }

        public static string GetPath()
        {
            string path = string.Empty;
            path = "C:/Program Files/PC Sync Manager/PhoneSuite.bin";
            if (File.Exists(path))
            {
                return path;
            }
            path = string.Empty;
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\PC Sync Manager");
            try
            {
                path = key.GetValue("UninstallString") as string;
                path = path.Substring(path.IndexOf('"') + 1);
                path = path.Replace("Uninst.isu\"", "PhoneSuite.bin");
            }
            catch
            {
            }
            finally
            {
                if (key != null)
                {
                    ((IDisposable) key).Dispose();
                }
            }
            return (path ?? string.Empty);
        }
        private static bool BeginReadNote(string str_bt, ref int emptyCount, ref bool isBeginning)
        {
            if ((str_bt == "1") || (str_bt == "63"))
            {
                isBeginning = true;
                emptyCount = 0;
            }
            else if (isBeginning)
            {
                if (str_bt == "0")
                {
                    emptyCount++;
                    if (emptyCount > 4)
                    {
                        emptyCount = 0;
                        isBeginning = false;
                    }
                }
                else if (emptyCount != 4)
                {
                    emptyCount = 0;
                    isBeginning = false;
                }
                else
                {
                    return true;
                }
            }
            return false;
        }
        private static List<Model> DoListItem(byte[] byteContent)
        {
            int index = 0;
            bool isBeginning = false;
            int emptyCount = 0;
            int num3 = 0;
            byte[] bytes = null;
            List<Model> list = new List<Model>();
            
            if (true) {
            	Model title = new Model ();
        	title.Date ="时间1";
        	title.Date2 ="";
        	title.Msg ="";
        	title.Number ="";
        	title.ISPNumber ="";
        	title.Position ="";
        	list.Add(title);

            }
            
            
            int length = byteContent.Length;
            while (index <= (length - 1))
            {

                //得到1个字节的数据
                string str = byteContent[index].ToString();
                //检查是否是是起始字节,或者其他什么字节
                if (BeginReadNote(str, ref emptyCount, ref isBeginning))
                {
                    Model item = new Model();
                    bytes = null;
                    //组合数字,将连续的两个byte组成 ()可能的)序号或者字节数
                    num3 = int.Parse(str);
                    num3 = (int.Parse(byteContent[index + 1].ToString()) * 0x100) + num3;
                    //序号在范围之外,则继续处理下一个字节,最多500条短信
                    if ((num3 <= 5) || (num3 >= 500))
                    {
                        isBeginning = false;
                        continue;
                    }
                    //
                    bytes = new byte[(num3 - 1) * 2];
                    index += 4;
                    int num5 = 0;
                    while (num5 <= (((num3 - 1) * 2) - 1))
                    {
                        bytes[num5] = byteContent[index];
                        num5++;
                        index++;
                    }
                    item.Msg = Encoding.Unicode.GetString(bytes).Trim(new char[1]);
                    bytes = null;
                    //直接跳过50字节
                    //这些自己记录存放位置，和短信中心的号码，这些内容是固定长度
                    index += 50;
                    num3 = 0;
                    //常规号码是0x0f,10086是0x6.10658830是0x9
                    //实际应该是显示的号码长度+1
                    if (false) {
                    	//原来的方法
	                    while (num3 != 15)//查找号码的前缀,实际此处应该是长度,0x010000
	                    {
	                        num3 = int.Parse(byteContent[index].ToString());
	                        index++;
	                    }
	                    
                    }else
                    {	
                    	while (num3 <2)//查找号码的前缀,实际此处应该是长度,0x010000
	                    {
                       num3 = int.Parse(byteContent[index].ToString());
	                   index++;
	                   }
                    }

                    //num3 = byteContent[index + 5];
                    //index += 6;
                    //////////////////////////////////////////
                    index += 3;
                    bytes = new byte[num3];
                    for (num5 = 0; num5 <= (num3 - 1); num5++)
                    {
                        bytes[num5] = byteContent[index];
                        index++;
                    }
                    item.Number = Encoding.Default.GetString(bytes).Trim(new char[1]);
                    bytes = null;
                    item.Date = string.Format("20{0:00}/{1:00}/{2:00} {3:00}:{4:00}:{5:00}", new object[] { byteContent[index + 2], byteContent[index + 4], byteContent[index + 5], byteContent[index + 6], byteContent[index + 7], byteContent[index + 8] });
                    index += 0x2a;
                    num3 = 0;
                    while (num3 == 0)
                    {
                        num3 = int.Parse(byteContent[index].ToString());
                        index++;
                    }
                    index += num3;
                    list.Add(item);
                    emptyCount = 0;
                    if (byteContent[index].ToString() != "1")
                    {
                        isBeginning = false;
                    }
                }
                index++;
            }
            return list;
        }

        private static string ReadFile(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return "";
            }
            using (StreamReader reader = new StreamReader(fileName, Encoding.GetEncoding("utf-16")))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

